<?php
namespace app\admin\model;

use think\Db;
class Order extends BaseModel
{
    protected $table = 'cz_order';
    protected $rule = [
        'uid'  =>  '',
    ];
    protected $msg = [
        'uid'  =>  '',
    ];
    protected $return = array();
    /**
     * 订单信息显示、分页搜索
     */
    public function pageQuerys()
    {
        $where = [];
        if (input("post.")) {
            $request = input("post.");
            if (! empty($request['identifier'])) {
                $where["order_sn"] = [
                    "like",
                    "%" . $request['identifier'] . "%"
                ];
            }
            if (! empty($request['contacts'])) {
                $where["contacts"] = [
                    "like",
                    "%" . $request['contacts'] . "%"
                ];
            }
            /*if ($request["tid"] != 0) {
                $where["tid"] = [
                    'EQ',
                    $request['tid']
                ];
            }*/
            if ($request["state"] != "") {
                $where["o.status"] = [
                    'EQ',
                    $request['state']
                ];
            }
        }
        $data = $this->alias("o")
            ->join("agl_goods g","o.goods_id = g.id","left")
            ->join("agl_member m","o.uid = m.id","left")->where($where)
            ->field('o.*,g.goods_name,m.username')
            ->order('id', 'desc')
            ->paginate(10, false, [
            'query' => request()->param()
        ]);
        return $data;
    }

    /**
     * 订单编辑
     *
     * @param unknown $data
     * @param unknown $profession
     */
    public function edit()
    {
        $data = input("post.");
        $r=false;
        if (! empty($data)) {
            $this->startTrans();
            $res = $this->where('id='. $data['id'])->setField("status",$data['category']);
            if(!$res){
                return $status = [
                    'code' => 0,
                    'msg' => '修改失败'
                ];
            }
            //订单详情
            $orderInfo = $this->getInfo(array("id"=>$data['id']));
            //用户详情
            $user = new Member();
            $userInfo = $user->getInfo(array("id"=>$orderInfo['uid']));

            $error = 0;
            if($data['category'] == 2){
                if($userInfo['pid'] != 0){
                    $pPrice = Db::name("order_success")->where("uid = ".$userInfo['pid'])->max("price");
                    $price = $pPrice > $orderInfo['price'] ? $orderInfo['price'] : $pPrice;
                    $super = Db::name('setting')->where('name', 'superiorsaleratio')->find();
                    $teams = Db::name('setting')->where('name', 'teamsaleratio')->find();
                    $Commission = $price * $super['value'] / 100;
                    $CommissionS = $Commission * $teams['value'] / 100;
                    $r1 = $user->where("id = ".$userInfo['pid'])->setInc("sale_money",$Commission);
                    $d = array(
                        'uid' => $userInfo['pid'],
                        'price' =>  $Commission,
                        'msg' => '您的下级'.$userInfo['username']."完成交易,您获得".$Commission."销售佣金",
                        'create_time' => date("Y-m-d H:i:s",time()),
                        'balance_type' => 1
                    );
                    $r2 = Db::name("account_log")->insert($d);
                    $da = array(
                        'uid' => $userInfo['id'],
                        'price' =>  $orderInfo['price'],
                        'create_time' => date("Y-m-d H:i:s",time())
                    );
                    $r3 = Db::name("order_success")->insert($da);
                    $r4 = $user->where("id = ".$orderInfo['uid'])->setInc("free_integral",$orderInfo['price']);
                    if($userInfo['level'] == 0){
                        $r5 = $user->where("id = " . $userInfo['id'])->setField("level", 1);
                    }else{
                        $r5 = true;
                    }
                    $r6 = $this->sub($userInfo['path'],$orderInfo['price'],$CommissionS,$userInfo['username']);
                    if($res && $r1!==false && $r2 && $r3 && $r4 && $r5 && $r6){
                        $r = true;

                    }else{
                        $r = false;
                    }
                }
            }else{
                $r = $user->where("id = ".$userInfo['id'])->setField("status",1);
            }
            if ($r) {
                $this->commit();
                return $status = [
                    'code' => 1,
                    'msg' => '修改成功'
                ];
            } else {
                $this->rollback();
                return $status = [
                    'code' => 0,
                    'msg' => '修改失败'
                ];
            }
        } else {
            return $status = [
                'code' => 0,
                'msg' => '修改失败'
            ];
        }
    }
    public function sub($path,$price,$CommissionS,$username){
        $user = new Member();
        $error = 0;
        $arrayId = array_values(array_filter(explode(",",$path)));
        $count = count($arrayId);
        for ($i = 0 ; $i < $count ; $i++){
            $arrUser = $user->getInfo(array("id"=>$arrayId[$i]));
            if(!empty($arrUser)) {
                $r2 = $user->where("id = " . $arrayId[$i])->setInc("team_price", $price);
                $r3 = $user->where("id = " . $arrayId[$i])->setInc("team_num");
                if (!$r2 || !$r3) {
                    $error++;
                } else {
                    if ($arrUser['level'] == 1) {
                        $countUser = $user->where("team_price >= 800000 and team_num >= 60 and pid = " . $arrayId[$i])->count();
                        if ($countUser >= 3) {
                            $r4 = $user->where("id = " . $arrayId[$i])->setField("level", 2);
                            $r5 = $user->where("id = " . $arrayId[$i])->setInc("sale_money", $CommissionS);
                            $d = array(
                                'uid' => $arrayId[$i],
                                'price' =>  $CommissionS,
                                'msg' => $username."完成交易，您获得".$CommissionS."团队销售佣金",
                                'create_time' => date("Y-m-d H:i:s",time()),
                                'balance_type' => 1
                            );
                            $r6 = Db::name("account_log")->insert($d);
                            if (!$r4 || !$r5 || $r6) {
                                $error++;
                            }
                        }
                    } elseif ($arrUser['level'] == 2) {
                        $r5 = $user->where("id = " . $arrayId[$i])->setInc("sale_money", $CommissionS);
                        if (!$r5) {
                            $error++;
                        }
                    }
                }
            }
        }
        if($error <= 0){
            return true;
        }else{
            return false;
        }
    }
    /**
     * 订单删除
     *
     * @param unknown $user_name
     * @param unknown $password
     */
    public function del()
    {
        $id = input("post.id");
        if ($id) {
            $query = $this->where("id", $id)->delete();
            if ($query) {
                return $status = [
                    'code' => 1,
                    'msg' => '删除成功'
                ];
            } else {
                return $status = [
                    'code' => 0,
                    'msg' => '删除失败'
                ];
            }
        }
    }

    /**
     * 订单批量删除
     *
     * @param unknown $typeName
     * @param unknown $typeName
     * @param unknown $query
     */
    public function proBatchDel()
    {
        $id = input("post.id");
        if ($id) {
            $query = $this->where("o_id", "in", $id)->delete();
            if ($query) {
                return $status = [
                    'code' => 1,
                    'msg' => '删除成功'
                ];
            } else {
                return $status = [
                    'code' => 0,
                    'msg' => '删除失败'
                ];
            }
        }
    }

    /**
     * 获取单条数据信息
     *
     * @param int $id
     * @param string $table
     * @param array $info
     */
    public function getById()
    {
        $id = input("id");
        $info = $this->where('id', $id)->find();
        return $info;
    }
}
